<?php
namespace application\admin\controller;
use application\common\controller\Base;
use application\common\model\User;
use think\exception\HttpException;

class Student extends Base
{
    public function addStudent() {
        if (! ($this->request->has('studentName','post') && $this->request->has('studentPassword','post'))) {
            $this->assign([
                'active' => [2,21],
                'title' => '添加学生',
                'messageCount' => 0,
            ]);
            return $this->fetch();
        } else {
            $studentName = $this->request->post('studentName');
            $studentPassword = $this->request->post('studentPassword');
            $user = new User();
            $user->user_name = $studentName;
            $user->user_password = md5($studentPassword);
            $user->user_role = 3;
            $result = $user->save();
            if ($result) {
                $this->redirect('index/index');
            }else {
                throw new HttpException(500);
            }
        }
    }
    public function manageStudent() {
        $user = new User();
        $result = $user->where(['user_role' => 3])->select();
        $this->assign([
            'title' => '删除学生',
            'active' => [2,22],
            'messageCount' => 0,
            'students' => $result,
        ]);
        return $this->fetch();
    }
    public function deleteStudent() {
        $user = new User();
        $students = input('post.items/a');
        $data = [];
        foreach ($students as $student) {
            $data = [
                'user_name' => $student,
                'user_role' => 3,
            ];
            User::destroy($data);
        }
        $result = $user->where(['user_role' => 3])->select();
        $this->assign([
            'title' => '删除学生',
            'active' => [2,22],
            'messageCount' => 0,
            'students' => $result,
        ]);
        $this->redirect('manageStudent');
    }
    public function notifyStudent() {
        $this->assign([
            'title' => '通知学生',
            'active' => [2,23],
            'messageCount' => 0,
        ]);
        return $this->fetch();
    }
    public function checkNameRepeat() {
        $user = new User();
        if (!$this->request->isAjax()) {
            $this->error("服务器错误！","admin/index/index");
        }else {
            $studentName = $this->request->post('name');
            $result = $user->where(['user_name' => $studentName,'user_role' => 3])->find();
            if ($result) {
                return '{"result":"true"}';
            }else {
                return '{"result":"false"}';
            }
        }
    }
}